package io.renren.modules.calculator.controller;


import io.renren.modules.calculator.dto.CalculatorRequest;
import io.renren.modules.calculator.dto.CalculatorResponse;
import io.renren.modules.calculator.service.CalculatorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;

@RestController
@RequestMapping("/calculator")
//@CrossOrigin(origins = "*")
public class CalculatorController {

    private final CalculatorService calculatorService;

    @Autowired
    public CalculatorController(CalculatorService calculatorService) {
        this.calculatorService = calculatorService;
    }

    @PostMapping("/calculate")
    public CalculatorResponse calculate(@RequestBody CalculatorRequest request) {
        try {
            BigDecimal result = calculatorService.calculate(
                    request.getExpression(),
                    request.getPrecision()
            );
            return new CalculatorResponse(true, result.toPlainString(), null);
        } catch (Exception e) {
            return new CalculatorResponse(false, null, e.getMessage());
        }
    }
}
